package com.dwb.common.upload;

import com.dwb.config.BizException;
import com.dwb.config.PhotoException;
import com.dwb.result.Result;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @Author manke
 * @Date 2020/6/23 17:13
 * @Version 0.0.1
 */
@RestController
@Api(value = "file", description = "文件上传控制器")
@RequestMapping("/upload")
public class Upload {

    @PostMapping("/uploadFile")
    public Result<String> uploadFileTest(@RequestParam("file") MultipartFile File) {

        return uploadFile(File);
    }

    /**
     * @Author wx
     * @Date 2020/6/25 15.55
     * 添加上传图片过滤
     * @Version 0.0.1
     */
    public Result<String> uploadFile(MultipartFile zipFile) {
        Result<String> result = Result.newSuccess();
        // 首先校验图片格式
        List<String> imageType = Lists.newArrayList("jpg", "jpeg", "png", "bmp", "gif");
        // 获取文件名，带后缀
        String originalFilename = zipFile.getOriginalFilename();
        // 获取文件的后缀格式
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
        if (imageType.contains(fileSuffix)) {
            // 只有当满足图片格式时才进来
            String targetFilePath = "D:\\test\\uploadTest";

            String fileName = UUID.randomUUID().toString().replace("-", "");
            File targetFile = new File(targetFilePath + File.separator + fileName);
            //如果文件目录不存在，就执行创建
            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs();
            }
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(targetFile);
                IOUtils.copy(zipFile.getInputStream(), fileOutputStream);
            } catch (IOException e) {
                return Result.newError("上传失败");
            } finally {
                try {
                    assert fileOutputStream != null;
                    fileOutputStream.close();
                } catch (IOException e) {
                    throw new BizException(-1, "未知错误");

                }
            }
            result.setDataMap(targetFilePath + "\\" + fileName);
            return result;
        } else {
            // 非法文件
            throw new PhotoException(-2,"图片格式错误,请上传jpg, jpeg, png, bmp, gif格式文件");
        }
    }
}


